package jdkrel._xml_parse._dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.Iterator;
import java.util.List;

/**
 * @author huangya
 * @date 2023/5/16
 */
public class Dom4jTest {

    public static void main(String[] args) {
//        Document doc = DocumentHelper.parseText(str) ;//从字符串中读取xml
//        Element rootElt = doc.getRootElement(); // 获取根节点
//        List first = rootElt.elements();
//        for (Iterator<?> its = first.iterator(); its.hasNext();) {
//            Element e = (Element) its.next();
//            List   second = e.elements();
//            for (Iterator<?> it = second.iterator(); it.hasNext();) {
//                Element t = (Element) it.next();
//                System.out.println(t.getText());
//            }
//        }

        SAXReader saxReader = SAXReader.createDefault();
        Document document = null;
        try {
            document = saxReader.read(Dom4jTest.class.getResourceAsStream("../books.xml"));
            List<Node> nodes = document.selectNodes("//book[author='Neal Stephenson']/title");
            Element rootElt = document.getRootElement(); // 获取根节点
            List first = rootElt.elements();
            for (Iterator<?> its = first.iterator(); its.hasNext();) {
                Element e = (Element) its.next();
                List   second = e.elements();
                for (Iterator<?> it = second.iterator(); it.hasNext();) {
                    Element t = (Element) it.next();
                    System.out.println(t.getText());
                }
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        Element ele = document.getRootElement();
    }

}
